package com.pen.changgou.goods.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.pen.changgou.common.core.entity.StatusCode;
import com.pen.changgou.common.core.utils.R;
import com.pen.changgou.goods.entity.Brand;
import com.pen.changgou.goods.service.BrandService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @author YaoDao
 * @version 1.0
 * @Description
 * @date 2020/11/25 0:56
 */
@Api(tags = "品牌管理")
@RestController
@RequestMapping("brand")
@Slf4j
public class BrandController {
    @Autowired
    BrandService brandService;

    @GetMapping("findAll")
    public R findAll() {
        List<Brand> brandList = brandService.list();
        return R.ok(brandList);
    }

    @GetMapping("/{id}")
    public R findById(@PathVariable Long id) {
        Brand brand = brandService.getById(id);
        return R.ok(brand);
    }

    @PostMapping("/add")
    public R add(@RequestBody Brand brand) {
        brandService.save(brand);
        return R.ok();
    }

    @PutMapping("/{id}")
    public R update(@RequestBody Brand brand, @PathVariable Long id) {
        brand.setId(id);

        brandService.updateById(brand);
        return R.ok();
    }

    @DeleteMapping("/{id}")
    public R delete(@PathVariable Long id) {
        brandService.removeById(id);
        return R.ok();
    }

    @GetMapping("/search")
    public R findList() {
        List<Brand> list = brandService.list(new QueryWrapper<>());
        return R.ok(list);
    }

    @GetMapping("/page")
    public R page(Page page, Brand brand) {
        return R.ok(brandService.page(page, Wrappers.query(brand)));

    }

    @GetMapping("/category/{id}")
    public R findBrandByCategoryId(@PathVariable(name = "id") Long categoryId) {
        return R.ok(brandService.findBrandByCategoryId(categoryId));

    }

    public QueryWrapper createQueryWrapper(Map<String, Object> params) {
        String name = params.getOrDefault("name", "").toString();
        String letter = params.getOrDefault("letter", "").toString();
        QueryWrapper queryWrapper = new QueryWrapper();
        if (StringUtils.isNotEmpty(name)) {
            queryWrapper.like("name", name);
        }
        if (StringUtils.isNotEmpty(letter)) {
            queryWrapper.like("letter", letter);
        }
        return queryWrapper;
    }

}
